package com.yingxin.yxerp.module.activiti.biz.service.process;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yingxin.yx.framework.commons.activiti.ApprovalStatus;
import com.yingxin.yx.framework.commons.activiti.dto.AuditDto;
import com.yingxin.yx.framework.commons.constant.CommonConst;
import com.yingxin.yx.framework.commons.enums.BusinessType;
import com.yingxin.yx.framework.commons.exception.BizException;
import com.yingxin.yxerp.module.activiti.api.BizProcessHandler;
import com.yingxin.yxerp.module.activiti.api.ProcessService;
import com.yingxin.yxerp.module.activiti.api.UpdateHandler;
import com.yingxin.yxerp.module.activiti.biz.entity.UpdateDateApply;
import com.yingxin.yxerp.module.activiti.biz.service.IUpdateDateApplyService;
import com.yingxin.yxerp.module.activiti.biz.vo.resp.UpdateDateApplyRespVo;
import com.yingxin.yxerp.module.activiti.entity.UpdateEntity;
import com.yingxin.yxerp.module.organization.entity.User;
import com.yingxin.yxerp.module.organization.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Component
public class UpdateDateApplyProcessHandler implements BizProcessHandler {

    @Autowired
    private ProcessService processService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IUpdateDateApplyService updateDateApplyService;

    @Autowired
    private UpdateHandlerRouter updateHandlerRouter;

    /**
     * 启动流程实例
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public void startProcessInstance(UpdateDateApply apply) {
        // 检查是否满足修改条件
        UpdateHandler handler = updateHandlerRouter.getHandler( apply.getBusinessType() );
        handler.check( apply.getBusinessId() );
        // startProcessInstance
        processService.startProcessInstance(
                BusinessType.XGSQ, apply.getId(), apply.getApplyNo(), getVariables( apply.getId() ) );
    }

    /**
     * 获取参数
     */
    @Override
    public Map<String, Object> getVariables(String businessId) {
        UpdateDateApply apply = updateDateApplyService.getById( businessId );
        User creator = userService.getById( apply.getCreatorId() );
        Map<String, Object> variables = new HashMap<>();
        if (StringUtils.isNotBlank(creator.getDeptId())) {
            variables.put("deptId", creator.getDeptId());
        }
        BusinessType businessType = BusinessType.getEnum(apply.getBusinessType());
        for (BusinessType type : BusinessType.values()){
            if (apply.getBusinessType().equals(type.getType())){
                variables.put("businessTypeList",businessType.getType());
                break;
            }
        }
        // 是否入客户名称
        variables.put( "isInMyCompany", apply.getIsInMyCompany() );
        return variables;
    }

    /**
     * 业务方法：公共
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void doCommonBiz(String id, AuditDto auditDto, ApprovalStatus approvalStatus) throws IllegalAccessException {
        // update ApprovalStatus
        UpdateWrapper<UpdateDateApply> uw = new UpdateWrapper<>();
        uw.lambda().set( UpdateDateApply::getApprovalStatus, approvalStatus.getStatus());
        uw.lambda().eq( UpdateDateApply::getId, id );
        updateDateApplyService.update(uw);
    }

    /**
     * 业务方法：单个任务审核通过
     */
    @Override
    public void doTaskApprovedBiz(String id, AuditDto auditDto, ApprovalStatus approvalStatus) throws IllegalAccessException {
        if ("spareDepartment".equals(auditDto.getFormKey())){
            UpdateWrapper<UpdateDateApply> uw = new UpdateWrapper<>();
            uw.lambda().set(UpdateDateApply::getIsPenalty,auditDto.getIsPenalty());
            if ( CommonConst.TRUE.equals( auditDto.getIsPenalty() ) ){
                BigDecimal penaltyMoney = BigDecimal.ZERO;
                if (StringUtils.isEmpty(auditDto.getPenaltyMoneyId())){
                    throw new BizException("罚款时，罚款金额不能小于等于 0 ");
                }
                //罚款
                if (auditDto.getPenaltyMoneyId().equals("00")){
                    if (auditDto.getOtherMoney() == null){
                        throw new BizException("罚款时，罚款金额不能小于等于 0 ");
                    }
                    penaltyMoney = auditDto.getOtherMoney();
                }else {
                    uw.lambda().set( UpdateDateApply::getPenaltyMoneyId, auditDto.getPenaltyMoneyId() );

                    penaltyMoney = auditDto.getPenaltyMoney();
                }
                if( penaltyMoney.compareTo( BigDecimal.ZERO ) <= 0 ){
                    throw new BizException("罚款时，罚款金额不能小于等于 0 ");
                }
                uw.lambda().set( UpdateDateApply::getPenaltyMoney, penaltyMoney );
            }else {
                if( StringUtils.isEmpty( auditDto.getAvoidPenaltyReason() ) ){
                    throw new BizException("免罚时，免罚原因必须输入！");
                }
                // 免罚
                uw.lambda().set( UpdateDateApply::getAvoidPenaltyReason, auditDto.getAvoidPenaltyReason() );
            }
            uw.lambda().eq( UpdateDateApply::getId, id );
            updateDateApplyService.update(uw);
        }
    }

    /**
     * 业务方法：整个流程审核通过
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void doProcessApprovedBiz(String id, AuditDto auditDto, ApprovalStatus approvalStatus) throws IllegalAccessException {
        UpdateDateApplyRespVo apply = updateDateApplyService.mapper().getVo( id );
        // 修改
        UpdateHandler handler = updateHandlerRouter.getHandler( apply.getBusinessType() );
        try {
            handler.update( getUpdateHandler( apply ) );
        }catch (Exception e ){}

        // 审核完成时间
        updateDateApplyService.updateApprovalTime( id );
    }

    /**
     * 业务方法：审核拒绝，审核撤销
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void doProcessUnapprovedBiz(String id, AuditDto auditDto, ApprovalStatus approvalStatus) throws IllegalAccessException {
        UpdateDateApplyRespVo apply = updateDateApplyService.mapper().getVo( id );
        // 修改
        UpdateHandler handler = updateHandlerRouter.getHandler( apply.getBusinessType() );
        try {
            handler.updateState( getUpdateHandler( apply ) );
        }catch (Exception e ){}
    }

    /**
     * 获取-传递参数的对象
     */
    private UpdateEntity getUpdateHandler(UpdateDateApplyRespVo apply ){

        UpdateEntity updateEntity = new UpdateEntity();
        // 业务单据id
        updateEntity.setBusinessId( apply.getBusinessId() );
        // 编辑备注
        updateEntity.setInvalidRemarks( apply.getReason() );
        // 编辑单id
        updateEntity.setApplyID( apply.getId() );
        // 编辑单编号
        updateEntity.setApplyNo( apply.getApplyNo() );
        // 编辑申请人id
        updateEntity.setApplyUserId( apply.getCreatorId().toString() );
        // 编辑申请人姓名
        updateEntity.setApplyUserName( apply.getCreatorName() );
        // 改后的对象 - 序列化
        updateEntity.setBill( apply.getBill() );
        // 改后的对象集 - 序列化
        updateEntity.setItems( apply.getItems() );
        // 改后的对象 - json
        updateEntity.setBillJson( apply.getBillJson() );
        // 改后的对象集 - json
        updateEntity.setItemsJson( apply.getItemsJson() );
        // 改前附件-json
        updateEntity.setOldAttachmentJson( apply.getOldAttachmentJson() );
        // 改后的对象集 - json
        updateEntity.setNewAttachmentJson( apply.getNewAttachmentJson() );
        // 原始单据状态
        updateEntity.setOriginalFlag(apply.getOriginalFlag() );

        return updateEntity;
    }

}
